package com.aiyun.securiy.login.security.custom;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.GenericFilter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.aiyun.securiy.login.security.UserList;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;


public class CustomRequestFilter extends GenericFilter {

	public static ThreadLocal<String> currentUser = new ThreadLocal<>();

	private final UserList userList;

	public CustomRequestFilter(UserList userList) {
		this.userList = userList;
	}


	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String authorization = request.getHeader("Authorization");
		Authentication authentication = userList.getAuthentication(authorization);
		if (authentication != null) {
			SecurityContextHolder.getContext().setAuthentication(authentication);
			currentUser.set(authentication.getPrincipal().toString());
		}
		filterChain.doFilter(servletRequest, servletResponse);
	}
}
